package com.mesnac.comm.filetransform;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

public class FileTransformUtil {
	
	private static final String tools = "pdf2swf";
	//swftool安装目录
	private String swftoolPath = "C:\\Program Files\\SWFTools\\";
	//pdf临时文件目录
	private String pdfPath ="/flexpaper/pdfFile";
	//swf文件存放路径
	private String swfPath ="/flexpaper/swfFile";
	//openoffice socket port
	private int prot = 8100;
	
	/**
	 * 文件流转化为pdf
	 * @param fileName
	 * @param in
	 * @param out
	 * @throws Exception
	 */
	public void documentIO2PDF(String fileName,InputStream in,OutputStream out) throws Exception{
		try{
			if(null == fileName&&fileName.indexOf(".")==-1){
				throw new IOException("No such File");
			}
			if(null == in){
				throw new IOException("inputstream is null");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		DocumentFormat pdfFormat = null;
		DocumentFormat xlsFormat = null;
		//
		
		DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
        pdfFormat = formatReg.getFormatByFileExtension("pdf");
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        if ("txt".equalsIgnoreCase(ext)) {
            xlsFormat = formatReg.getFormatByFileExtension("odt");
        }else if("pdf".equalsIgnoreCase(ext)){
        	//if base is pdf , then copy direct
        	while(true){
        		byte[] b = new byte[2097152];
        		int readline = in.read(b);
        		if(readline == -1){
        			in.close();
        			out.flush();
        			out.close();
        			break;
        		}else{
        			out.write(b,0,readline);
        		}
        	}
        	return;
        }else {
            xlsFormat = formatReg.getFormatByFileExtension(ext);
        }
        OpenOfficeConnection openOfficeSocketConnection = null;
        // 文件转换
        try {
            openOfficeSocketConnection = new SocketOpenOfficeConnection("127.0.0.1",prot);
            openOfficeSocketConnection.connect();

            DocumentConverter converter = new OpenOfficeDocumentConverter(openOfficeSocketConnection);
            converter.convert(in, xlsFormat, out, pdfFormat);

            openOfficeSocketConnection.disconnect();
        } catch (ConnectException e) {
        	System.out.println("文件转换错误：[ openoffice 服务连接失败 ]:" + e.getMessage());
            throw new Exception("文件转换错误：[ openoffice 服务连接失败 ]:" + e.getMessage());
        } finally {
            if (openOfficeSocketConnection != null) {
                openOfficeSocketConnection.disconnect();
                openOfficeSocketConnection = null;
            }
        }
	}
	/**
	 * pdf 转化为swf
	 * @param pdf
	 * @param swf
	 */
	public void pdf2swf(File pdf,File swf){
		if(swf.exists()){
			return;
		}
		try{
			String command = "";
			if(isWindowSystem()){
				command = swftoolPath + tools+".exe -t "+pdf.getPath()+" -o " +swf.getPath()+" -T 9";
			}else{
				command = tools+" -t"+pdf.getPath()+" -o"+swf.getPath()+" -T 9";
			}
			System.out.println(command);
			Process process = Runtime.getRuntime().exec(command);
			
			//清理进程
			new flushProcess(process.getInputStream()).start();
			new flushProcess(process.getErrorStream()).start();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			
		}
		
	}
	/**
	 * 关闭操作流
	 * @param in
	 * @param out
	 */
	private void closeIO(InputStream in,OutputStream out){
		if(in != null){
			try{
				in.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			in = null;
		}
		if(out!=null){
			try{
				out.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			out = null;
		}
		
	}
	
	public boolean isWindowSystem(){
		String sys = System.getProperty("os.name");
		return sys.toLowerCase().indexOf("windows")!=-1?true:false;
	}
	private class flushProcess extends Thread{

		private InputStream flush;
		public flushProcess(InputStream in){
			this.flush = in;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			
			BufferedReader br = new BufferedReader(new InputStreamReader(flush));
			try{
				while(br.readLine()!=null);
			}catch(IOException e){
				e.printStackTrace();
			}finally{
				if(br!=null){
					try{
						br.close();
					}catch(IOException e){
						e.printStackTrace();
					}
				}
			}
		}
		
	}
	
	/**
	 * 文件转化为swf
	 * @param fileName
	 * @param in
	 * @param swfFileName
	 * @param webapp
	 * @return
	 * @throws Exception
	 */
	public String document2swf(String fileName,InputStream in,String swfFileName,String webapp) throws Exception{
		if(fileName == null ||in == null){
			return null;
		}
		String pdf = swfFileName+".pdf";
		String swf = swfFileName+".swf";
		File pdfFile = new File(webapp+pdfPath+File.separator+pdf);		
		File swfFile = new File(webapp+swfPath+File.separator+swf);	
		if(pdfFile.exists())
			pdfFile.delete();
		if(swfFile.exists())
			swfFile.delete();
		pdfFile = new File(webapp+pdfPath+File.separator+pdf);
		swfFile = new File(webapp+swfPath+File.separator+swf);
		if(!swfFile.exists()){
			if(!pdfFile.exists()){
				OutputStream out = null;
				try{
					out = new FileOutputStream(pdfFile);
					this.documentIO2PDF(fileName, in, out);
				}catch(FileNotFoundException e){
					e.printStackTrace();
				}finally{
					closeIO(in,out);
				}
			}
			this.pdf2swf(pdfFile, swfFile);
		}
		//这个地方因为之前采用多线程，而前端显示需要等待，我们需要判断一下，转换是否完成
		while(!swfFile.exists())
			Thread.sleep(1000);
		return swf;
	}
	
	
	public static void main(String args[]) throws Exception{
		File a = new File("");
		System.out.println(a.getAbsolutePath());
		System.out.println(a.getCanonicalPath());
		System.out.println(File.separator);
		
		FileTransformUtil tran = new FileTransformUtil();
		String doc = "E:/Visual.doc";
		String swf = "tmp";
		File docFile = new File(doc);
		File swfFile = new File(swf);
		InputStream input = new FileInputStream(docFile);
		tran.document2swf(doc, input, swf, "D:/tomcat6.0/webapps/pinshuoinfor");
	}
}
